import { ModuleDeclaration } from 'ts-morph'
import { UseOptions } from '../../interface/cmd'
import { RequestMethods } from '../../interface/typescript'

/**
 *
 * @param modules 获取到ts文件中的所有模块定义
 * @param callback 回调函数，遍历模块，并返回单个模块信息
 * @param parentName 递归到当前模块，所有父级namespace的名称，通过.符号分割
 */
export function handleModule(
  modules: ModuleDeclaration[],
  callback: (module: ModuleDeclaration, fullName: string) => void,
  parentName = ''
) {
  for (const module of modules) {
    const children = module.getModules()
    const hasModule = children.length > 0
    const fullName = `${parentName ? `${parentName}.` : ''}${module.getName()}`
    callback(module, fullName)
    if (hasModule) {
      handleModule(children, callback, fullName)
    }
  }
}

export const tsPerfix = (tsDefineFilename: string, option: UseOptions) =>
  `/* eslint-disable */
import request from './request.ts';
import api from './${tsDefineFilename.replace('.ts', '')}';
const baseUrl = '${option.baseUrl}'
`

export const tsLine = (
  apiName: string,
  reqName: string,
  rspName: string,
  requestMethod: RequestMethods,
  baseUrl: string
) => `
export function ${apiName}(req: api.${reqName}): Promise<api.${rspName}> {
  return request.${requestMethod}<api.${rspName}>('${baseUrl}/${apiName}', ${
  requestMethod === 'post' ? 'req' : '{ params: req }'
});
};
`
export const jsPerfix = (tsDefineFilename: string, option: UseOptions) =>
  `/* eslint-disable */
import request from './request.js';
import api from './${tsDefineFilename.replace('.ts', '')}';
const baseUrl = '${option.baseUrl}'
`

export const jsLine = (
  apiName: string,
  reqName: string,
  rspName: string,
  requestMethod: RequestMethods,
  baseUrl: string
) => `
/**
 * 
 * @param {api.${reqName}} req
 * @returns {Promise<api.${rspName}>}
 */
 export function ${apiName}(req){
  return request.${requestMethod}('${baseUrl}/${apiName}', ${
  requestMethod === 'post' ? 'req' : '{ params: req }'
});
 };
`
